/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package session.manager;

import entity.Player;
import entity.Resource;
import entity.Storage;
import entity.StoragePK;
import java.util.Collection;
import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.ejb.TransactionManagement;
import javax.ejb.TransactionManagementType;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

/**
 *
 * @author antonio
 */
@Stateless
@TransactionManagement(TransactionManagementType.CONTAINER)
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public class ResourceManagerBean implements ResourceManagerBeanLocal {

    @PersistenceContext(unitName = "BrowserGame-ejbPU")
    private EntityManager entityManager;

    @Override
    public void initResources(String username) {
        Player player = entityManager.find(Player.class, username);
        Collection<Resource> resources = findAll();
        System.out.print(resources);
        for (Resource r : resources) {
            StoragePK pk = new StoragePK(player.getUsername(), r.getName());
            Storage storage = new Storage(pk);
            storage.setPlayer1(player);
            storage.setResource1(r);
            storage.setAmount(r.getInitAmount());
            entityManager.persist(storage);
        }
    }

    @Override
    public void decrese(String username, String resourceName, int amount) {
        StoragePK pk = new StoragePK(username, resourceName);
        Storage storage = entityManager.find(Storage.class, pk);
        if (storage.getAmount() < amount) {
            throw new IllegalArgumentException("Quantita' di risorse non sufficienti");
        }
        storage.setAmount(storage.getAmount() - amount);
        entityManager.merge(storage);
    }

    @Override
    public void increse(String username, String resourceName, int amount) {
        StoragePK pk = new StoragePK(username, resourceName);
        Storage storage = entityManager.find(Storage.class, pk);
        storage.setAmount(storage.getAmount() + amount);
        entityManager.merge(storage);
    }

    @Override
    public int getResourceAmount(String username, String resourceName) {
        StoragePK pk = new StoragePK(username, resourceName);
        Storage storage = entityManager.find(Storage.class, pk);
        return storage.getAmount();
    }

    @Override
    public Collection<Resource> findAll() {
        javax.persistence.criteria.CriteriaQuery cq = entityManager.getCriteriaBuilder().createQuery();
        cq.select(cq.from(Resource.class));
        return entityManager.createQuery(cq).getResultList();
    }

    @Override
    public void edit(Storage storage) {
        entityManager.merge(storage);
    }

    @Override
    public void edit(Resource resource) {
        entityManager.merge(resource);
    }
}
